package vn.com.pavibook.admin.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import vn.com.pavibook.admin.service.AudioBookService;
import vn.com.pavibook.domain.model.AudioBook;
import vn.com.pavibook.domain.model.PagingInfo;
import vn.com.pavibook.domain.model.SearchResult;
import vn.com.pavibook.model.vo.AudioBookVO;
import vn.com.pavibook.utils.DataHelper.Paging;

@Controller
public class AudioBookController {
	private static final Logger LOGGER = Logger
			.getLogger(AudioBookController.class);

	@Autowired
	private AudioBookService audioBookService;

	@RequestMapping(value = "admin/add-audio-book", method = RequestMethod.GET)
	public String openAddAudioPage(Model model) {
		AudioBookVO audioBookVO = new AudioBookVO();
		model.addAttribute("audioBookVO", audioBookVO);
		model.addAttribute("audioCurrent", "");
		model.addAttribute("imageCurrent", "");
		model.addAttribute("titlePage", "Thêm audio");
		return "admin/add-audio-book";
	}

	@RequestMapping(value = "admin/audio-book-info", method = RequestMethod.GET)
	public String viewAudioBooks(Model model) {
		PagingInfo pagingInfo = new PagingInfo(Paging.OFFSET.getValue(), 1);
		SecurityContext context = SecurityContextHolder.getContext();
		String username = context.getAuthentication().getName();
		SearchResult<AudioBook> bunchOfAudioBook = audioBookService
				.getAudioBookByPushlisher(username, pagingInfo);
		List<AudioBook> audioBooks = new ArrayList<AudioBook>();
		if (bunchOfAudioBook != null
				&& bunchOfAudioBook.getSearchResult() != null) {
			audioBooks = bunchOfAudioBook.getSearchResult();
		}
		model.addAttribute("audioBooks", audioBooks);
		model.addAttribute("pagingInfo", bunchOfAudioBook.getPagingInfo());
		return "admin/audio-book-info";
	}

	@RequestMapping(value = "admin/delete-audio-book", method = RequestMethod.GET)
	public String deleteAudio(Model model, @RequestParam("id") int id) {
		audioBookService.deleteAudioBook(id);
		return "redirect:audio-book-info";
	}

	@RequestMapping(value = "admin/edit-audio-book", method = RequestMethod.GET)
	public String EditAudio(Model model, @RequestParam("id") int id) {
		SearchResult<AudioBook> audioBook = audioBookService
				.getAudioBookById(id);
		AudioBookVO audioBookVO = audioBook.getSearchResult().get(0)
				.convertToAudioBookVO();
		createAudioBookModelAttr(model, audioBookVO);
		model.addAttribute("titlePage", "Sửa audio");
		return "admin/add-audio-book";
	}

	private void createAudioBookModelAttr(Model model, AudioBookVO audioBookVO) {
		String audioCurrent = audioBookVO.getUrlAudio().substring(
				audioBookVO.getUrlAudio().lastIndexOf("/") + 1);
		String imageCurrent = audioBookVO.getImageUrl().substring(
				audioBookVO.getImageUrl().lastIndexOf("/") + 1);
		model.addAttribute("audioCurrent", audioCurrent);
		model.addAttribute("imageCurrent", imageCurrent);
		model.addAttribute("audioBookVO", audioBookVO);
		model.addAttribute("titlePage", "Sửa audio");
	}

	@RequestMapping(value = "admin/save-adio-book", method = RequestMethod.POST)
	public String saveAudioBook(Model model,
			@ModelAttribute("audioBookVO") @Valid AudioBookVO audioBookVO,
			BindingResult result, HttpServletRequest request) {
		SecurityContext context = SecurityContextHolder.getContext();
		String username = context.getAuthentication().getName();
		if (result.hasErrors()) {
			createAudioBookModelAttr(model, audioBookVO);
			return "admin/add-audio-book";
		}
		boolean uploadSucess = false;

		try {
			uploadSucess = audioBookService.uploadAudio(audioBookVO, username,
					request);
		} catch (Exception e) {
			LOGGER.error(e);
			createAudioBookModelAttr(model, audioBookVO);
			return "admin/add-audio-book";
		}

		if (uploadSucess) {
			audioBookService.save(audioBookVO.convertToAudioBook());
		} else {
			createAudioBookModelAttr(model, audioBookVO);
			return "admin/add-audio-book";
		}

		return "redirect:audio-book-info";
	}

	@RequestMapping(value = "admin/searchAudioBook", method = RequestMethod.POST)
	public String searchAudioBook(Model model,
			@RequestParam("pageIndex") int pageIndex,
			@RequestParam("keyword") String keyword) {
		SecurityContext context = SecurityContextHolder.getContext();
		String username = context.getAuthentication().getName();
		
		PagingInfo pagingInfo = new PagingInfo(10, pageIndex);
		SearchResult<AudioBook> result = new SearchResult<AudioBook>();
		if(StringUtils.isEmpty(keyword)){
			result = audioBookService.getListAudioBookByUsername(username, pagingInfo, null);
		} else {
			result = audioBookService.getListAudioBookByUsername(username, pagingInfo, keyword);
		}
		List<AudioBook> audioBooks = result.getSearchResult();
		
		model.addAttribute("audioBooks", audioBooks);
		model.addAttribute("pagingInfo", pagingInfo);
		model.addAttribute("keyword", keyword);
		return "admin/audio-book-info";
	}
}
